<!--
 * @Author: RAY_HUI 1541917867@qq.com
 * @Date: 2025-07-08 17:58:46
 * @LastEditors: RAY_HUI 1541917867@qq.com
 * @LastEditTime: 2025-08-15 17:35:02
 * @FilePath: \website-reconstruction---vue\src\components\sections\contact\Message.vue
 * @Description: 
 * 
 * Copyright (c) 2025 by ${git_name_email}, All Rights Reserved. 
-->
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import type { FormField } from '@/types/selfdefine/Layout'
import { postFormData } from '@/api/xyybackend/submission.js'
import { getRandomAnimation } from '@/utils/tools/tools'
import {
  getPartTitleByIdAndLang,
  getFormFieldList,
} from '@/api/xyybackend/getVoList.js'
import { ElMessage } from 'element-plus'
import { storeToRefs } from 'pinia'
import { useLangStore } from '@/stores/langStore'

// 1. 获取响应式语言状态 ✅
const { currentLang } = storeToRefs(useLangStore())

// 2. 原始数据（来自后端，包含中英文）
const titleContent = ref<{
  partTitle: string
  content: string
  partTitleTranslate?: string
  contentTranslate?: string
}>({
  partTitle: '',
  content: '',
  partTitleTranslate: '',
  contentTranslate: '',
})

const formFields = ref<FormField[]>([])

// 3. 【核心】computed 动态返回当前语言的文案
const displayedTitleContent = computed(() => {
  const isZh = currentLang.value === 'zh'
  return {
    title: isZh
      ? titleContent.value.partTitle
      : titleContent.value.partTitleTranslate || titleContent.value.partTitle,
    content: isZh
      ? titleContent.value.content
      : titleContent.value.contentTranslate || titleContent.value.content,
  }
})

// 4. 【核心】computed 动态返回翻译后的表单字段
const displayedFormFields = computed(() => {
  return formFields.value.map((field) => {
    const isZh = currentLang.value === 'zh'
    return {
      ...field,
      placeholder: isZh
        ? field.placeholder
        : field.placeholderTranslate || field.placeholder,
    }
  })
})

// 5. 页面加载时请求一次（包含翻译字段）
onMounted(async () => {
  const id = 14
  try {
    const [res, resB] = await Promise.all([
      getPartTitleByIdAndLang({ id: 14, lang: 'en' }), // 后端自动根据 lang 返回对应翻译
      getFormFieldList({ lang: 'en' }),
    ])

    // 后端已返回中英文字段，我们存原始数据
    if (res.data) {
      titleContent.value = res.data // 包含 partTitle, partTitleTranslate 等
    }

    if (resB?.rows) {
      formFields.value = resB.rows // 每个字段包含 placeholder, placeholderTranslate
    }
  } catch (error) {
    console.error('获取数据失败:', error)
  }
})
//提交的表单
//表单封装的操作
const fillFormData = () => {
  // console.log('表单数据:', formFields.value)

  // ✅ 1. 手动前端验证
  for (let field of displayedFormFields.value) {
    // 检查 required 且 value 为空（null, undefined, ''）
    if (field.required && (!field.value || field.value.trim() === '')) {
      // ❌ 验证失败，弹出提示并阻止提交
      ElMessage.error(`请填写 ${field.placeholder || field.name}`)
      // console.log(`验证失败：${field.name} 不能为空`)
      return // 阻止后续执行
    }
  }

  // ✅ 2. 验证通过，继续执行
  // 转成对象
  const formData = displayedFormFields.value.reduce((acc, field) => {
    acc[field.name] = field.value
    return acc
  }, {})
  // console.log('提交对象:', formData)

  // 3. 发送请求
  postFormData(formData)
    .then((response) => {
      ElMessage.success('提交成功！感谢您的反馈。')
      // 4. 清空数据
      formFields.value.forEach((field) => {
        field.value = ''
        // 如果需要，也可以重置其他状态，比如验证错误标志
        // field.hasError = false
      })
    })
    .catch((error) => {
      console.error('提交失败:', error)
      ElMessage.error('提交失败，请稍后重试。')
      // 注意：失败时通常不清空数据
    })
}
</script>

<template>
  <div class="section-padding contact-form-map wow ${getRandomAnimation}">
    <div class="container">
      <div class="row">
        <!-- 表单区域 -->
        <div :class="`col-lg-6 `">
          <div class="section-header style-left">
            <div class="section-heading">
              <h3 class="text-custom-black">
                {{ displayedTitleContent.title }}
              </h3>
              <div class="section-description">
                <p class="text-light-dark">
                  {{ displayedTitleContent.content }}
                </p>
              </div>
            </div>
          </div>
          <div id="msgBox" style="display: block"></div>

          <!-- 表单 -->
          <form id="contactMail" method="POST" class="mb-md-80">
            <div class="row wow ${getRandomAnimation}">
              <!-- 动态渲染输入项 -->
              <template
                v-for="(field, index) in displayedFormFields"
                :key="index"
              >
                <div
                  :class="`col-md-6 wow ${getRandomAnimation}`"
                  v-if="field.type != 'textArea'"
                >
                  <div class="form-group">
                    <input
                      :type="field.type"
                      :name="field.name"
                      class="form-control form-control-custom"
                      :placeholder="field.placeholder"
                      :required="field.required"
                      v-model="field.value"
                    />
                  </div>
                </div>

                <!-- 多行文本域单独处理 -->
                <div class="col-md-12" v-else>
                  <div class="form-group">
                    <textarea
                      :type="field.type"
                      :name="field.name"
                      class="form-control form-control-custom"
                      :placeholder="field.placeholder"
                      :required="field.required"
                      rows="5"
                      v-model="field.value"
                    ></textarea>
                  </div>
                  <button
                    type="button"
                    class="btn-first btn-submit"
                    @click="fillFormData()"
                  >
                    提交
                  </button>
                </div>
              </template>
            </div>
          </form>
        </div>

        <!-- 地图区域 -->
        <div class="col-lg-6" style="overflow-x: auto; width: 100%">
          <div
            :class="`contact-map full-height  `"
            style="min-width: 1200px; width: max-content; height: 100%"
          >
            <iframe
              class="full-height"
              src="https://www.amap.com"
              sandbox="allow-scripts allow-same-origin allow-popups allow-forms allow-pointer-lock"
              allowfullscreen
              style="border: 0; width: 100%; height: 100%; overflow-x: auto"
            ></iframe>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
